﻿
using Module_Debug.Hardware;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace Module_Debug.x_Novatek
{
    public partial class NT37900 : Form
    {

        CaSDK CaSDKObj = new CaSDK();
        CRC16 CRCData = new CRC16();
        private double[,] D_lums;//目标值-单色
        private double[] D_lum = new double[25];//目标值-白色
        private byte[] Send_buf = new byte[1];
        List<string> lines;
        private byte[] Rec_tmp = new byte[1];
        private byte[] Rec_tmp1 = new byte[1];
        private List<byte> buffer = new List<byte>(4096);//默认分配1/16页内存，并始终限制不允许超过  
        private bool Listening = false;//是否没有执行完invoke相关操作   
        private bool IClosing = false;//是否正在关闭串口，执行Application.DoEvents，并阻止再次invoke  
        //创建类型为Person的对象集合
        List<Setting.Gamma_Property> Diven_Gamma = new List<Setting.Gamma_Property>();
        List<Setting.Offset_Property> Diven_Offset = new List<Setting.Offset_Property>();
        //监听NT37701A挂载
        string[] DBV_SET = { "", "" };
        string[] GAMMA_SET = { "", "" };
        private List<string> ImageType;

        public static bool firstGammaFlag = true;   //初次打开子窗体标志位

        public NT37900()
        {
            //frmMain.frmain = DOE_NT37900;
            InitializeComponent();
            //frmMain.frmain.Child_window_hide_already = true;
            //frmMain.frmain.Child_Gamma_Window_Open_Enable = false;//防止重复开启子窗体  

            //string[] s = { ".bmp", ".dsc" };
            //his.ImageType = new List<string>(s);
        }

        #region  //---NT37900专用界面  打开与否的相关处理  以及 串口 返回数据 处理- --- serial Data----
        private void NT37900_Gamma_FormClosed(object sender, FormClosedEventArgs e)
        {

        }
        private void NT37900_Gamma_VisibleChanged(object sender, EventArgs e)
        {
        }
        static byte[] GetCRCArray(byte[] arr, Byte speedflag)   //处理命令数组，在其头尾增加包头以及CRC校验值，处理后的数据可以直接发送至下位机
        {
            CRC16 CRCData = new CRC16();

            int arrNumbuer;                                                                                                                                                                                                                                                                                                                                             //51
            arrNumbuer = arr.Length;
            arrNumbuer += 6;
            byte[] Send_Datax = new byte[arrNumbuer];
            Send_Datax[0] = 0x9f;
            Send_Datax[1] = (byte)(speedflag << 4);
            Send_Datax[2] = Convert.ToByte(arr.Length + 1);  //为兼容下位机命令，此位置填待传输有效数据长度+1 

            Send_Datax[arr.Length + 3] = 0xFF;  //添加结束标志位
            arr.CopyTo(Send_Datax, 3);//合并数组头 4个Byte 标志位
            //计算校验码                                                 
            CRCData.CalculateCrc16(Send_Datax, out Send_Datax[arrNumbuer - 2], out Send_Datax[arrNumbuer - 1]);
            return Send_Datax;
        }
        #endregion //---串口返回数据处理- --- serial Data----
        private void GR_WriteRead_Click(object sender, EventArgs e)          //上位机使用通用命令读写方式操作DDIC
        {
            string str = regSend.Text.ToString();
            byte DDICReg; byte readnum;
            string[] arr;
            arr = str.Split(',');
            Setting.TempRecord.cmdLen = arr.Length + 5;
            //Send_buf = new byte[Setting.TempRecord.cmdLen];
            //Send_buf[2] = Convert.ToByte(arr.Length);
            Button btnTmp = (Button)sender;
            //Send_buf[0] = 0x6B;

            switch (btnTmp.Name)
            {
                case "writeReg":
                    {
                        String text;
                        text = regSend.Text;
                        frmMain.frmain.txtProcessDrivercode(text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        if (rBt_LP_DCS_Long_Write.Checked | rBt_LP_DCS_Short_Write.Checked | rBt_LP_Gerneric_Long_Write.Checked | rBt_LP_Gerneric_Short_Write.Checked)
                        {
                            frmMain.frmain.SendCmd(0);  //低速
                        }
                        else
                        {
                            frmMain.frmain.SendCmd(4); //高速
                        }
                        frmMain.frmain.showmsg("命令已下发");
                    }
                    break;
                case "readReg":
                    {
                        //NT37900_0XFE_XX = 0x00;
                        //Send_buf[1] = 0x02;
                        DDICReg = byte.Parse(Convert.ToUInt32(arr[0], 16).ToString());
                        try
                        {
                            readnum = byte.Parse(Convert.ToUInt32(arr[1], 16).ToString());
                            frmMain.frmain.GeneralRegRead(DDICReg, readnum);
                        }
                        catch
                        {
                            //txttip.Text += "读参数异常....\r\n";
                            frmMain.frmain.showmsg("读参数异常....");
                        }

                    }
                    break;

                default:
                    break;
            }
            //for (int i = 0; i < arr.Length; i++)
            //{
            //    Send_buf[3 + i] = byte.Parse(Convert.ToUInt32(arr[i], 16).ToString());
            //}
            //CRCData.CalculateCrc16(Send_buf, out Send_buf[Setting.TempRecord.cmdLen - 2], out Send_buf[Setting.TempRecord.cmdLen - 1]);
            //try
            //{
            //    frmMain.frmain.comPort.Write(Send_buf, 0, Setting.TempRecord.cmdLen);
            //}
            //catch
            //{
            //    MessageBox.Show("串口有误，请检查", "错误");
            //}
            frmMain.frmain.T1.Enabled = false;
            frmMain.frmain.T1.Interval = 2000;
            frmMain.frmain.T1.Enabled = true;
        }           //上位机使用通用命令读写方式操作DDIC
        private void NT37900610C_CWriteReg_Click(object sender, EventArgs e)  ////通过下位机  项目定制  向DDIC写入命令--该写法建议后续废弃
        {
            string str = regSend.Text.ToString();
            string[] arr;
            arr = str.Split(',');
            Setting.TempRecord.cmdLen = arr.Length + 5;
            Send_buf = new byte[Setting.TempRecord.cmdLen];
            Send_buf[2] = Convert.ToByte(arr.Length);
            Button btnTmp = (Button)sender;
            Send_buf[0] = 0x6B;
            switch (btnTmp.Name)
            {
                case "writeReg":
                    {
                        NT37900_0XFE_XX = 0x00;
                        Send_buf[1] = 0x01;
                    }
                    break;
                case "readReg":
                    {
                        NT37900_0XFE_XX = 0x00;
                        Send_buf[1] = 0x02;
                    }
                    break;

                default:
                    break;
            }
            for (int i = 0; i < arr.Length; i++)
            {
                Send_buf[3 + i] = byte.Parse(Convert.ToUInt32(arr[i], 16).ToString());
            }
            CRCData.CalculateCrc16(Send_buf, out Send_buf[Setting.TempRecord.cmdLen - 2], out Send_buf[Setting.TempRecord.cmdLen - 1]);
            try
            {
                frmMain.frmain.comPort.Write(Send_buf, 0, Setting.TempRecord.cmdLen);
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
            }
            frmMain.frmain.T1.Enabled = false;
            frmMain.frmain.T1.Interval = 2000;
            frmMain.frmain.T1.Enabled = true;
        }  //通过下位机  项目定制  向DDIC写入命令
        private void btnRun_Click(object sender, EventArgs e)   //---复位屏幕，重新点屏
        {
            frmMain.frmain.btnRun_Click(frmMain.frmain.btnRun, e);
        }
        #region    //---Auto Gamma----------------------
        private void btnSaveGamma_Click(object sender, EventArgs e)
        {
            string tepGammaR = ""; string tepGammaG = ""; string tepGammaB = "";
            string tepstr = "";
            string NT37900Gammatxt = "";
            //Int16[] GammaPoint = new Int16[25] { 1, 2, 3, 5, 7, 11, 15, 19, 23, 27, 31, 35, 39, 47, 55, 63, 71, 79, 95, 111, 127, 159, 191, 223, 255 };
            int index = 0;// txt51Dbv.GetFirstCharIndexOfCurrentLine();
            int line = 0;// txt51Dbv.GetLineFromCharIndex(index);
            Int16 gdattmp;
            {
                Button btnTmp = (Button)sender;
                switch (btnTmp.Name)
                {
                    case "btnSaveGamma":
                        {
                            //以文本形式保存
                            if (chkGammaFormatForNT37900.Checked && chkNT37900dircshow.Checked)
                            {
                                for (int i = 0; i < (this.GammaReg_dataGridView.Rows.Count - 1); i++)
                                {
                                    gdattmp = Convert.ToInt16(this.GammaReg_dataGridView.Rows[i].Cells[2].Value.ToString(), 10);
                                    tepGammaR += Convert.ToString(gdattmp) + "\r\n";
                                    gdattmp = Convert.ToInt16(this.GammaReg_dataGridView.Rows[i].Cells[3].Value.ToString(), 10);
                                    tepGammaG += Convert.ToString(gdattmp) + "\r\n";
                                    gdattmp = Convert.ToInt16(this.GammaReg_dataGridView.Rows[i].Cells[4].Value.ToString(), 10);
                                    tepGammaB += Convert.ToString(gdattmp) + "\r\n";
                                }
                                string str = "";
                                for (int i = 0; i < 25; i++)
                                {
                                    str += Point_NT37900[i] + "\r\n";
                                }
                                SaveFileDialog txt = new SaveFileDialog();
                                txt.Filter = @"txt文件(*.txt)|*.txt|所有文件(*.*)|*.*";
                                //string GammaStr = "//-----保存Gamma 寄存器值-----\r\n";
                                if (txt.ShowDialog() == DialogResult.OK)
                                {
                                    if (txt.FileName == " ")
                                    {
                                        return;
                                    }
                                    StreamWriter gsw = null; //文件流
                                    gsw = new StreamWriter(txt.FileName, false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")
                                    try
                                    {
                                        tepGammaB = tepGammaB.Substring(0, tepGammaB.Length - 2);
                                        gsw.Write(str + tepGammaR + tepGammaG + tepGammaB);
                                        gsw.Dispose(); //释放资源
                                        gsw.Close(); //关闭数据流
                                        MessageBox.Show("保存Gamma 寄存器保存OK！", "系统提示：");
                                    }
                                    catch
                                    {
                                        MessageBox.Show("保存Gamma 寄存器保存时发生错误，请再试！", "系统提示：");
                                    }
                                }
                            }
                            else if (chkGammaFormatForNT37900.Checked && !chkNT37900dircshow.Checked)
                            {
                                for (int i = 0; i < (this.GammaReg_dataGridView.Rows.Count - 1); i++)
                                {
                                    gdattmp = Convert.ToInt16(this.GammaReg_dataGridView.Rows[i].Cells[2].Value.ToString());      //变换格式                                    
                                    tepGammaR += string.Format("{0:X2}", (gdattmp >> 8)) + "," + string.Format("{0:X2}", (gdattmp & 0xff)) + ",";
                                    gdattmp = Convert.ToInt16(this.GammaReg_dataGridView.Rows[i].Cells[3].Value.ToString());
                                    tepGammaG += string.Format("{0:X2}", (gdattmp >> 8)) + "," + string.Format("{0:X2}", (gdattmp & 0xff)) + ",";
                                    gdattmp = Convert.ToInt16(this.GammaReg_dataGridView.Rows[i].Cells[4].Value.ToString());
                                    tepGammaB += string.Format("{0:X2}", (gdattmp >> 8)) + "," + string.Format("{0:X2}", (gdattmp & 0xff)) + ",";
                                }
                                tepstr = "B0," + tepGammaR.Substring(1 - 1, 48 - 1) + "\r\n" + "B1," + tepGammaR.Substring(1 + 48 - 1, 48 - 1) + "\r\n" + "B2," + tepGammaR.Substring(1 + 48 + 48 - 1, 48 - 1) + "\r\n" + "B3," + tepGammaR.Substring(1 + 48 + 48 + 48 - 1, 6 - 1) + "\r\n";
                                NT37900Gammatxt += "//GammaR, L-->H : ...\r\n" + tepstr + "\r\n";

                                tepstr = "B4," + tepGammaG.Substring(1 - 1, 48 - 1) + "\r\n" + "B5," + tepGammaG.Substring(1 + 48 - 1, 48 - 1) + "\r\n" + "B6," + tepGammaG.Substring(1 + 48 + 48 - 1, 48 - 1) + "\r\n" + "B7," + tepGammaG.Substring(1 + 48 + 48 + 48 - 1, 6 - 1) + "\r\n";
                                NT37900Gammatxt += "//GammaG, L-->H : ...\r\n" + tepstr + "\r\n";

                                tepstr = "B8," + tepGammaB.Substring(1 - 1, 48 - 1) + "\r\n" + "B9," + tepGammaB.Substring(1 + 48 - 1, 48 - 1) + "\r\n" + "BA," + tepGammaB.Substring(1 + 48 + 48 - 1, 48 - 1) + "\r\n" + "BB," + tepGammaB.Substring(1 + 48 + 48 + 48 - 1, 6 - 1) + "\r\n";
                                NT37900Gammatxt += "//GammaB, L-->H : ...\r\n" + tepstr + "\r\n";

                                string str = "";
                                //if (rbt_NT37900_Gamma9.Checked) { str = "// ---Gamma 9 九--  -\r\n //Gamma set 9--  -\r\n bf,08\r\n"; }
                                //else if (rbt_NT37900_Gamma10.Checked) { str = "// ---Gamma 10 十---\r\n //Gamma set 10---\r\n bf,09\r\n"; }
                                //else if (rbt_NT37900_Gamma1.Checked) { str = "// ---Gamma 1 一---\r\n //Gamma set 1---\r\n bf,00\r\n"; }
                                //else if (rbt_NT37900_Gamma2.Checked) { str = "// ---Gamma 2 二---\r\n //Gamma set 2---\r\n bf,01\r\n"; }
                                //else if (rbt_NT37900_Gamma3.Checked) { str = "// ---Gamma 3 三---\r\n //Gamma set 3---\r\n bf,02\r\n"; }
                                //else if (rbt_NT37900_Gamma4.Checked) { str = "// ---Gamma 4 四---\r\n //Gamma set 4---\r\n bf,03\r\n"; }
                                //else if (rbt_NT37900_Gamma5.Checked) { str = "// ---Gamma 5 五---\r\n //Gamma set 5---\r\n bf,04\r\n"; }
                                //else if (rbt_NT37900_Gamma6.Checked) { str = "// ---Gamma 6 六---\r\n //Gamma set 6---\r\n bf,05\r\n"; }
                                //else if (rbt_NT37900_Gamma7.Checked) { str = "// ---Gamma 7 七---\r\n //Gamma set 7---\r\n bf,06\r\n"; }
                                //else if (rbt_NT37900_Gamma8.Checked) { str = "// ---Gamma 8 八---\r\n //Gamma set 8---\r\n bf,07\r\n"; }
                                //------------------------------------------------------------------------
                                SaveFileDialog txt = new SaveFileDialog();
                                txt.Filter = @"txt文件(*.txt)|*.txt|所有文件(*.*)|*.*";
                                //string GammaStr = "//-----保存Gamma 寄存器值-----\r\n";
                                if (txt.ShowDialog() == DialogResult.OK)
                                {
                                    if (txt.FileName == " ")
                                    {
                                        return;
                                    }
                                    StreamWriter gsw = null; //文件流
                                    gsw = new StreamWriter(txt.FileName, false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")
                                    try
                                    {
                                        //richTextBox_GC_In.Text += str + NT37900Gammatxt;
                                        gsw.Write(str + NT37900Gammatxt);
                                        gsw.Dispose(); //释放资源
                                        gsw.Close(); //关闭数据流
                                        MessageBox.Show("保存Gamma 寄存器保存OK！", "系统提示：");
                                    }
                                    catch
                                    {
                                        MessageBox.Show("保存Gamma 寄存器保存时发生错误，请再试！", "系统提示：");
                                    }
                                }
                            }
                            else if (!chkGammaFormatForNT37900.Checked && chkNT37900dircshow.Checked)
                            {
                                for (int i = 0; i < (this.GammaReg_dataGridView.Rows.Count - 1); i++)
                                {
                                    gdattmp = Convert.ToInt16(this.GammaReg_dataGridView.Rows[i].Cells[2].Value.ToString());      //变换格式
                                    tepGammaR += string.Format("{0:X2}", (gdattmp >> 8)) + "," + string.Format("{0:X2}", (gdattmp & 0xff)) + ",";
                                    gdattmp = Convert.ToInt16(this.GammaReg_dataGridView.Rows[i].Cells[3].Value.ToString());
                                    tepGammaG += string.Format("{0:X2}", (gdattmp >> 8)) + "," + string.Format("{0:X2}", (gdattmp & 0xff)) + ",";
                                    gdattmp = Convert.ToInt16(this.GammaReg_dataGridView.Rows[i].Cells[4].Value.ToString());
                                    tepGammaB += string.Format("{0:X2}", (gdattmp >> 8)) + "," + string.Format("{0:X2}", (gdattmp & 0xff)) + ",";
                                }

                                tepstr = "B0," + tepGammaR.Substring(1 - 1, 48 - 1) + "\r\n" + "B1," + tepGammaR.Substring(1 + 48 - 1, 48 - 1) + "\r\n" + "B2," + tepGammaR.Substring(1 + 48 + 48 - 1, 48 - 1) + "\r\n" + "B3," + tepGammaR.Substring(1 + 48 + 48 + 48 - 1, 6 - 1) + "\r\n";
                                NT37900Gammatxt += "//GammaR, L-->H : ...\r\n" + tepstr + "\r\n";

                                tepstr = "B4," + tepGammaG.Substring(1 - 1, 48 - 1) + "\r\n" + "B5," + tepGammaG.Substring(1 + 48 - 1, 48 - 1) + "\r\n" + "B6," + tepGammaG.Substring(1 + 48 + 48 - 1, 48 - 1) + "\r\n" + "B7," + tepGammaG.Substring(1 + 48 + 48 + 48 - 1, 6 - 1) + "\r\n";
                                NT37900Gammatxt += "//GammaG, L-->H : ...\r\n" + tepstr + "\r\n";

                                tepstr = "B8," + tepGammaB.Substring(1 - 1, 48 - 1) + "\r\n" + "B9," + tepGammaB.Substring(1 + 48 - 1, 48 - 1) + "\r\n" + "BA," + tepGammaB.Substring(1 + 48 + 48 - 1, 48 - 1) + "\r\n" + "BB," + tepGammaB.Substring(1 + 48 + 48 + 48 - 1, 6 - 1) + "\r\n";
                                NT37900Gammatxt += "//GammaB, L-->H : ...\r\n" + tepstr + "\r\n";
                                //------------------------------------------------------------------------
                                string str = "";
                                //if (rbt_NT37900_Gamma9.Checked) { str = "// ---Gamma 9 九-- -\r\n //Gamma set 9-  --\r\n bf,08\r\n"; }
                                //else if (rbt_NT37900_Gamma10.Checked) { str = "// ---Gamma 10 十---\r\n //Gamma set 10---\r\n bf,09\r\n"; }
                                //else if (rbt_NT37900_Gamma1.Checked) { str = "// ---Gamma 1 一---\r\n //Gamma set 1---\r\n bf,00\r\n"; }
                                //else if (rbt_NT37900_Gamma2.Checked) { str = "// ---Gamma 2 二---\r\n //Gamma set 2---\r\n bf,01\r\n"; }
                                //else if (rbt_NT37900_Gamma3.Checked) { str = "// ---Gamma 3 三---\r\n //Gamma set 3---\r\n bf,02\r\n"; }
                                //else if (rbt_NT37900_Gamma4.Checked) { str = "// ---Gamma 4 四---\r\n //Gamma set 4---\r\n bf,03\r\n"; }
                                //else if (rbt_NT37900_Gamma5.Checked) { str = "// ---Gamma 5 五---\r\n //Gamma set 5---\r\n bf,04\r\n"; }
                                //else if (rbt_NT37900_Gamma6.Checked) { str = "// ---Gamma 6 六---\r\n //Gamma set 6---\r\n bf,05\r\n"; }
                                //else if (rbt_NT37900_Gamma7.Checked) { str = "// ---Gamma 7 七---\r\n //Gamma set 7---\r\n bf,06\r\n"; }
                                //else if (rbt_NT37900_Gamma8.Checked) { str = "// ---Gamma 8 八---\r\n //Gamma set 8---\r\n bf,07\r\n"; }
                                //Points_LV.Text += (str + NT37900Gammatxt);
                                //richTextBox_GC_In.Text += (str + NT37900Gammatxt);
                            }
                            else
                            {//保存
                                SaveFileDialog sf = new SaveFileDialog(); //对话框
                                sf.Filter = @"csv文件(*.csv)|*.csv|所有文件(*.*)|*.*"; //定义保存的文件的类型

                                string str = "灰阶序号,灰阶亮度,reg_R,reg_G,reg_B\r\n";
                                if (sf.ShowDialog() == DialogResult.OK) //如果确定保存
                                {
                                    if (sf.FileName == "") return; //如果没有输入文件名
                                    try
                                    {
                                        StreamWriter sw = null; //文件流
                                        sw = new StreamWriter(sf.FileName, false, Encoding.UTF8);
                                        for (int i = 0; i < (this.GammaReg_dataGridView.Rows.Count - 1); i++)
                                        {
                                            str = str + this.GammaReg_dataGridView.Rows[i].Cells[0].Value.ToString() + ","
                                                + this.GammaReg_dataGridView.Rows[i].Cells[1].Value.ToString() + ","
                                                + this.GammaReg_dataGridView.Rows[i].Cells[2].Value.ToString() + ","
                                                + this.GammaReg_dataGridView.Rows[i].Cells[3].Value.ToString() + ","
                                                + this.GammaReg_dataGridView.Rows[i].Cells[4].Value.ToString() + "\r\n";
                                        }
                                        sw.WriteLine(str);
                                        sw.Dispose(); //释放资源
                                        sw.Close(); //关闭数据流
                                        MessageBox.Show("数据保存OK！", "系统提示：");

                                    }
                                    catch
                                    {
                                        MessageBox.Show("数据保存时发生错误，请再试！", "系统提示：");
                                    }
                                }

                            }
                        }
                        break;
                    case "btnLoadGamma":
                        {
                            this.GammaReg_dataGridView.Rows.Clear();
                            OpenFileDialog sf = new OpenFileDialog();
                            int Line_Count = 0;
                            string strtmp = "";
                            sf.Filter = @"csv文件(*.csv)|*.csv|所有文件(*.*)|*.*"; //定义文件的类型
                            sf.Title = "数据导入";
                            if (sf.ShowDialog() == DialogResult.OK) //如果确定保存
                            {
                                FileStream fs = new FileStream(sf.FileName, FileMode.Open, FileAccess.Read);
                                StreamReader streamReader = new StreamReader(fs, Encoding.GetEncoding("GBK"));
                                streamReader.BaseStream.Seek(0, SeekOrigin.Begin);
                                string strLine = streamReader.ReadLine();
                                while (!string.IsNullOrEmpty(strLine))
                                {
                                    strtmp = strtmp + strLine + ",";
                                    strLine = streamReader.ReadLine(); //循环读取下一行
                                    Line_Count++;
                                }
                                fs.Close(); //关闭流
                                streamReader.Close();
                                string[] arrtmp = strtmp.Split(new Char[] { ',' });
                                for (int j = 1; j <= Line_Count - 1; j++)
                                {
                                    DataGridViewRow Row1 = new DataGridViewRow();
                                    GammaReg_dataGridView.Rows.Add(Row1);
                                }
                                try
                                {
                                    for (int i = 0; i < Line_Count - 1; i++)//有一行标题
                                    {
                                        GammaReg_dataGridView.Rows[i].Cells[0].Value = arrtmp[5 * (i + 1) + 0];
                                        GammaReg_dataGridView.Rows[i].Cells[1].Value = arrtmp[5 * (i + 1) + 1];
                                        GammaReg_dataGridView.Rows[i].Cells[2].Value = arrtmp[5 * (i + 1) + 2];
                                        GammaReg_dataGridView.Rows[i].Cells[3].Value = arrtmp[5 * (i + 1) + 3];
                                        GammaReg_dataGridView.Rows[i].Cells[4].Value = arrtmp[5 * (i + 1) + 4];
                                        //------------------------------------
                                        index = txt51Dbv.GetFirstCharIndexOfCurrentLine();
                                        line = txt51Dbv.GetLineFromCharIndex(index);
                                        {
                                            GammaValx[line, i, 0] = Convert.ToUInt32(arrtmp[(5 * (i + 1)) + 2]);
                                            GammaValx[line, i, 1] = Convert.ToUInt32(arrtmp[(5 * (i + 1)) + 3]);
                                            GammaValx[line, i, 2] = Convert.ToUInt32(arrtmp[(5 * (i + 1)) + 4]);
                                            //GammaValue[i, 0] = Convert.ToUInt32(arrtmp[(5 * (i + 1)) + 2]);
                                            //GammaValue[i, 1] = Convert.ToUInt32(arrtmp[(5 * (i + 1)) + 3]);
                                            //GammaValue[i, 2] = Convert.ToUInt32(arrtmp[(5 * (i + 1)) + 4]);
                                        }
                                    }
                                    MessageBox.Show("数据导入OK！", "提示：");
                                }
                                catch
                                {
                                    MessageBox.Show("数据导入时发生错误！", "提示：");
                                }
                            }
                        }
                        break;
                    case "btn_CAS200_Clean":
                        {
                            DialogResult dr = MessageBox.Show("确认清空列表数据吗？", "系统提示", MessageBoxButtons.OKCancel);
                            if (dr == DialogResult.OK)
                            {
                                this.GammaReg_dataGridView.Rows.Clear();
                            }
                        }
                        break;

                    default: break;
                }
            }
        }
        private byte Gammnum;
        private void NT37900_CGamma_Button_Click(object sender, EventArgs e)   //通过6130 定制命令读取其Gamma值，但此方法因2K平台未适配，故无效
        {
            this.GammaReg_dataGridView.Rows.Clear();
            Send_buf = new byte[157];
            Button btnTmp = (Button)sender;
            Send_buf[0] = 0x6B;
            Send_buf[2] = 0x05; //Length

            ///Gamma ..select
            //if (rbt_NT37900_Gamma1.Checked)
            //{
            //    Gammnum = 0x00;
            //}
            //else if (rbt_NT37900_Gamma2.Checked)
            //{
            //    Gammnum = 0x01;
            //}
            //else if (rbt_NT37900_Gamma3.Checked)
            //{
            //    Gammnum = 0x02;
            //}
            //else if (rbt_NT37900_Gamma4.Checked)
            //{
            //    Gammnum = 0x03;
            //}
            //else if (rbt_NT37900_Gamma5.Checked)
            //{
            //    Gammnum = 0x04;
            //}
            //else if (rbt_NT37900_Gamma6.Checked)
            //{
            //    Gammnum = 0x05;
            //}
            //else if (rbt_NT37900_Gamma7.Checked)
            //{
            //    Gammnum = 0x06;
            //}
            //else if (rbt_NT37900_Gamma8.Checked)
            //{
            //    Gammnum = 0x07;
            //}
            //else if (rbt_NT37900_Gamma9.Checked)
            //{
            //    Gammnum = 0x08;
            //}
            //else if (rbt_NT37900_Gamma10.Checked)
            //{
            //    Gammnum = 0x09;
            //}
            Send_buf[3] = (byte)numGammaPage.Value;
            switch (btnTmp.Name)
            {
                case "NT37900_GammaR":
                    {
                        NT37900_0XFE_XX = 0x00;
                        Send_buf[1] = 0x09;
                        Send_buf[4] = 0x96;   //每组gamma数量

                    }
                    break;
                case "NT37900_GammaW":
                    {
                        GammaValueFormat_Click(null, null);
                        byte rh = 1;
                        byte rl = 1;
                        byte gh = 1;
                        byte gl = 1;
                        byte bh = 1;
                        byte bl = 1;

                        GammaValueSet(rh, rl, gh, gl, bh, bl, GammaValueTeparr);
                    }
                    break;
                case "NT37900_OTP":
                    {
                        NT37900_0XFE_XX = 0x00;
                        Send_buf[1] = 0x0D;
                        // Send_buf[4] = 0x96;   //每组gamma数量
                    }
                    break;

                default:
                    break;
            }
            Setting.TempRecord.cmdLen = Send_buf[2] + 5;
            CRCData.CalculateCrc16Start_Length(Send_buf, 0, Setting.TempRecord.cmdLen - 2, out Send_buf[Setting.TempRecord.cmdLen - 2], out Send_buf[Setting.TempRecord.cmdLen - 1]);
            try
            {
                frmMain.frmain.comPort.Write(Send_buf, 0, Setting.TempRecord.cmdLen);
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
            }
            frmMain.frmain.T1.Enabled = false;
            frmMain.frmain.T1.Interval = 2000;
            frmMain.frmain.T1.Enabled = true;
        }

        private double D_x, D_y;
        //private int index = 0;
        private double lum_off, x_off, y_off;
        private double R_x = 0.67;//
        private double R_y = 0.33;
        private double G_x = 0.22;
        private double G_y = 0.71;
        private double B_x = 0.14;
        private double B_y = 0.06;
        private uint[,] GammaValue = new uint[25, 3];//保存当前Gammavalue
        private double auto_lum;  //  存放获取到的产品亮度值
        private double auto_x;
        private double auto_y;        //  存放获取到的产品亮度 色坐标 x,y
        private int index = 1;  //AutoGamma 调整顺序
        private int flag1 = 1;
        private int flag2 = 1;
        private int flag3 = 1;
        bool lastdirupR = true; bool lastdirupG = true; bool lastdirupB = true; // Gamma 调整方向
        private uint step_l = 1;   //Gamma 调节步长
        byte rstep = 16; byte gstep = 16; byte bstep = 16;
        bool STOPAutoGammaFlag = false;     //AutoGamma 停止标志位，解决定时器禁止后AutoGamma无法停止的问题
        byte[] GammaValueTeparr = new byte[53 * 3]; //存放格式化后的GammaValue，以便于直接下发至DDIC
        byte[] ReadBackarr = new byte[32];  //暂存下位机返回数据
        bool GammaReadBackFlag = false; // 下位机返回数据完成标志位
        byte[] GammaValueReceived = new byte[50 * 3]; //存放从下位机接收过来的GammaValue        
        bool ReceivOKFlag = false;
        private int[] Point_NT37900 = new int[24] {//---Gamma绑点数据，这里的数据仅供参考---
            0,3,5,7,11,15,19,23,27,31,35,39,47,55,63,71,79,95,111,127,159,191,223,255};

        //byte GPN =  (byte) Point_NT37900.Length; // 获取Gamma绑点数量
        byte GPN = 0; //保存Gamma绑点数量
        private void btnCalGammaValue_Click(object sender, EventArgs e)   //计算对应绑点灰阶值，并连同暂存的Gammavale显示在窗体表格上
        {
            txtGammaNode_TextChanged(null, null);
            //Points_LV.Clear();
            GPN = (byte)Point_NT37900.Length; // 获取Gamma绑点数量
            D_lum = new double[GPN];
            {
                this.GammaReg_dataGridView.Rows.Clear();
            }
            for (byte i = 0; i < GPN; i++)
            {
                D_lum[i] = (Math.Pow((Point_NT37900[i] / 255.0), Convert.ToDouble(txtVT_gamma.Text)) * Convert.ToDouble(txtVT_lum.Text));
                DataGirdShow(i, GammaValue[i, 0], GammaValue[i, 1], GammaValue[i, 2]);
                frmMain.frmain.textBox1.Text += "Gamma Node" + i + ": " + Point_NT37900[i] + "\r\n";
            }
        }
        private void GammaValueFormat_Click(object sender, EventArgs e)   //GammaValue 值拆分成 Byte 并与实际地址进行转换 以便于后续处理发送至下位机
        {
            //txtGammadisplay.Text = "B0"; //Convert.ToString(要转的数,16);
            for (int i = 0; i < 9; i++)
            {
                // txtGammadisplay.Text += "," + Convert.ToString(GammaValue[i, 0] >> 8, 16) + "," + Convert.ToString(GammaValue[i, 0] & 0xff, 16);
                GammaValueTeparr[0] = 0xb0;
                GammaValueTeparr[2 * i + 1] = (byte)(GammaValue[i, 0] >> 8);
                GammaValueTeparr[2 * i + 2] = (byte)(GammaValue[i, 0] & 0xff);
            }
            //txtGammadisplay.Text += "\r\n" + "B1"; //Convert.ToString(要转的数,16);
            for (int i = 9; i < 18; i++)
            {
                //txtGammadisplay.Text += "," + Convert.ToString(GammaValue[i, 0] >> 8, 16) + "," + Convert.ToString(GammaValue[i, 0] & 0xff, 16);
                GammaValueTeparr[0 + 19] = 0xb1;
                GammaValueTeparr[2 * i + 2] = (byte)(GammaValue[i, 0] >> 8);
                GammaValueTeparr[2 * i + 3] = (byte)(GammaValue[i, 0] & 0xff);
            }
            //txtGammadisplay.Text += "\r\n" + "B2"; //Convert.ToString(要转的数,16);
            for (int i = 18; i < 25; i++)
            {
                //txtGammadisplay.Text += "," + Convert.ToString(GammaValue[i, 0] >> 8, 16) + "," + Convert.ToString(GammaValue[i, 0] & 0xff, 16);
                GammaValueTeparr[0 + 38] = 0xb2;
                GammaValueTeparr[2 * i + 3] = (byte)(GammaValue[i, 0] >> 8);
                GammaValueTeparr[2 * i + 4] = (byte)(GammaValue[i, 0] & 0xff);
            }
            // txtGammadisplay.Text += "\r\n" + "B3"; //Convert.ToString(要转的数,16);----------------------
            //---------------------------------------------------
            for (int i = 0; i < 9; i++)
            {
                // txtGammadisplay.Text += "," + Convert.ToString(GammaValue[i, 0] >> 8, 16) + "," + Convert.ToString(GammaValue[i, 0] & 0xff, 16);
                GammaValueTeparr[53 + 0] = 0xb3;
                GammaValueTeparr[53 + 2 * i + 1] = (byte)(GammaValue[i, 1] >> 8);
                GammaValueTeparr[53 + 2 * i + 2] = (byte)(GammaValue[i, 1] & 0xff);
            }
            //txtGammadisplay.Text += "\r\n" + "B1"; //Convert.ToString(要转的数,16);
            for (int i = 9; i < 18; i++)
            {
                //txtGammadisplay.Text += "," + Convert.ToString(GammaValue[i, 0] >> 8, 16) + "," + Convert.ToString(GammaValue[i, 0] & 0xff, 16);
                GammaValueTeparr[53 + 0 + 19] = 0xb4;
                GammaValueTeparr[53 + 2 * i + 2] = (byte)(GammaValue[i, 1] >> 8);
                GammaValueTeparr[53 + 2 * i + 3] = (byte)(GammaValue[i, 1] & 0xff);
            }
            //txtGammadisplay.Text += "\r\n" + "B2"; //Convert.ToString(要转的数,16);
            for (int i = 18; i < 25; i++)
            {
                //txtGammadisplay.Text += "," + Convert.ToString(GammaValue[i, 0] >> 8, 16) + "," + Convert.ToString(GammaValue[i, 0] & 0xff, 16);
                GammaValueTeparr[53 + 0 + 38] = 0xb5;
                GammaValueTeparr[53 + 2 * i + 3] = (byte)(GammaValue[i, 1] >> 8);
                GammaValueTeparr[53 + 2 * i + 4] = (byte)(GammaValue[i, 1] & 0xff);
            }
            //---------------------------------------------------
            for (int i = 0; i < 9; i++)
            {
                // txtGammadisplay.Text += "," + Convert.ToString(GammaValue[i, 0] >> 8, 16) + "," + Convert.ToString(GammaValue[i, 0] & 0xff, 16);
                GammaValueTeparr[106 + 0] = 0xb6;
                GammaValueTeparr[106 + 2 * i + 1] = (byte)(GammaValue[i, 2] >> 8);
                GammaValueTeparr[106 + 2 * i + 2] = (byte)(GammaValue[i, 2] & 0xff);
            }
            //txtGammadisplay.Text += "\r\n" + "B1"; //Convert.ToString(要转的数,16);
            for (int i = 9; i < 18; i++)
            {
                //txtGammadisplay.Text += "," + Convert.ToString(GammaValue[i, 0] >> 8, 16) + "," + Convert.ToString(GammaValue[i, 0] & 0xff, 16);
                GammaValueTeparr[106 + 0 + 19] = 0xb7;
                GammaValueTeparr[106 + 2 * i + 2] = (byte)(GammaValue[i, 2] >> 8);
                GammaValueTeparr[106 + 2 * i + 3] = (byte)(GammaValue[i, 2] & 0xff);
            }
            //txtGammadisplay.Text += "\r\n" + "B2"; //Convert.ToString(要转的数,16);
            for (int i = 18; i < 25; i++)
            {
                //txtGammadisplay.Text += "," + Convert.ToString(GammaValue[i, 0] >> 8, 16) + "," + Convert.ToString(GammaValue[i, 0] & 0xff, 16);
                GammaValueTeparr[106 + 0 + 38] = 0xb8;
                GammaValueTeparr[106 + 2 * i + 3] = (byte)(GammaValue[i, 2] >> 8);
                GammaValueTeparr[106 + 2 * i + 4] = (byte)(GammaValue[i, 2] & 0xff);
            }
        }
        private void GammaValueSet(byte rh, byte rl, byte gh, byte gl, byte bh, byte bl, byte[] Gammaarr)  //把拆分后Gamma值按照DDIC 规定格式排列后送入DDIC
        {   //通过高速方式向第一条Gamma写入一组Gamma值
            byte[] TepArr;
            try
            {
                TepArr = new byte[] { 6, 0xf0, 0x55,0xaa,0x52,0x08, 0x02,
                    2, 0xcc, 0x10,
                    2, 0xbf, 0x07,
                     };  //byte[] TepArr;

                if (chkAODMode.Checked)
                {
                    Gammnum = (byte)(numGammaPage.Value);
                }
                else if (!chkSaveGammavalue.Checked)
                {
                    Gammnum = (byte)(numGammaPage.Value);
                }
                else Gammnum = (byte)(numGammaPage.Value);

                TepArr[12] = Gammnum; //设定对应Gamma序号

                frmMain.frmain.comPort.Write(GetCRCArray(TepArr, 4), 0, TepArr.Length + 6);//循环部分，每段数据结尾  
                //-----------------  
                TepArr = new byte[] {
                19,0xB0, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 ,00, 00 ,
                19,0xB1, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 ,00, 00 ,
                15,0xB2, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 ,

                19,0xB3, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 ,00, 00 ,
                19,0xB4, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 ,00, 00 ,
                15,0xB5, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 ,

                19,0xB6, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 ,00, 00 ,
                19,0xB7, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 ,00, 00 ,
                15,0xB8, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 ,
                
                //2,0xc4, 0x00
                };

                Array.Copy(Gammaarr, 0, TepArr, 1, 19);
                Array.Copy(Gammaarr, 19, TepArr, 1 + 20 * 1, 19);
                Array.Copy(Gammaarr, 38, TepArr, 1 + 20 * 2, 15);

                Array.Copy(Gammaarr, 53, TepArr, 1 + 20 * 2 + 16, 19);
                Array.Copy(Gammaarr, 72, TepArr, 1 + 20 * 3 + 16, 19);
                Array.Copy(Gammaarr, 91, TepArr, 1 + 20 * 4 + 16, 15);

                Array.Copy(Gammaarr, 106, TepArr, 1 + 20 * 4 + 32, 19);
                Array.Copy(Gammaarr, 125, TepArr, 1 + 20 * 5 + 32, 19);
                Array.Copy(Gammaarr, 144, TepArr, 1 + 20 * 6 + 32, 15);
                //public static void Copy(
                //Array sourceArray,
                //int sourceIndex,
                //Array destinationArray,
                //int destinationIndex,
                //int length); 
                frmMain.frmain.comPort.Write(GetCRCArray(TepArr, 4), 0, TepArr.Length + 6);//循环部分，每段数据结尾
                //Application.DoEvents();//重点，必须加上，否则父子窗体都假死
            }
            catch
            {
                frmMain.frmain.showmsg("串口问题Gamma无法写入，请检查");
                frmMain.frmain.ForeColor = Color.OrangeRed;
                return;
            }
        }
        private void btnAutoGammas_Click(object sender, EventArgs e)
        {
            chkGammaLoadBMP.Checked = true;
            if (frmMain.frmain.btnCal_manual.Tag.ToString() != "0calDone")
            {
                frmMain.frmain.btnCal_manual.Enabled = true;
                MessageBox.Show("需要提前连接410并校准~", "提示：");
                return;
            }
            txtGammaNode_TextChanged(null, null);
            numStep_ValueChanged(null, null);
            int flag = 1;
            JumpGammaAdjustFlag = false;
            frmMain.frmain.textBox1.ForeColor = Color.Black;
            STOPAutoGammaFlag = false;
            GPN = (byte)Point_NT37900.Length; // 获取Gamma绑点数量
            double Lr_d, Lg_d, Lb_d;
            D_lums = new double[GPN, 3];
            D_lum = new double[GPN];
            index = 1;  //Gamma绑点序号，第一个绑点通常对应255灰阶
            flag1 = flag2 = flag3 = 1;
            rstep = 16;
            gstep = 16;
            bstep = 16;
            frmMain.frmain.textBox1.Text += "GammaValue最大值被限定为: " + GammaValueMax + "\r\n";
            TimTest.Start();
            TimeNow = DateTime.Now; //开始计时

            for (int i = 0; i < GPN; i++)  //计算相应绑点对应的亮度值
            {
                D_lum[i] = (Math.Pow((Point_NT37900[i] / 255.0), Convert.ToDouble(txtVT_gamma.Text)) * Convert.ToDouble(txtVT_lum.Text));
            }

            D_x = Convert.ToDouble(txtVT_x.Text);  //获取调节目标色坐标 x
            D_y = Convert.ToDouble(txtVT_y.Text); ////获取调节目标色坐标 y
            Lr_d = R_y * ((D_y - G_y) * (B_x - D_x) + (D_x - G_x) * (D_y - B_y)) / B_y / ((D_y - G_y) * (D_x - R_x) + (D_x - G_x) * (R_y - D_y));
            Lb_d = 1.0;
            Lg_d = G_y * ((D_y - R_y) * (B_x - D_x) + (D_x - R_x) * (D_y - B_y)) / B_y / ((D_y - R_y) * (D_x - G_x) + (D_x - R_x) * (G_y - D_y));

            for (int i = 0; i < GPN; i++)   // 通过色坐标已经亮度计算各绑点R/G/B分量对应的亮度值
            {
                D_lums[i, 0] = D_lum[i] * Lr_d / (Lr_d + Lg_d + Lb_d);
                D_lums[i, 1] = D_lum[i] * Lg_d / (Lr_d + Lg_d + Lb_d);
                D_lums[i, 2] = D_lum[i] * Lb_d / (Lr_d + Lg_d + Lb_d);
            }
            labTargetlum.Text = "Tar:" + D_lum[GPN - index].ToString("f4").Substring(0, 6);   //显示当前绑点对应的目标亮度值
            //Lv.ToString().Substring(0, 6);
            switch (flag)
            {
                case 1://寄存器值与亮度正比
                    {
                        //lum_off = Convert.ToDouble(txtVT_loff.Text);
                        x_off = Convert.ToDouble(txtVT_xoff.Text);   //获取色坐标允差范围
                        y_off = Convert.ToDouble(txtVT_yoff.Text);
                        frmMain.frmain.numPatternR.Value = Point_NT37900[GPN - index];     //设定绑点灰阶
                        //numPatternG.Value = Point_NT37900[GPN - index];
                        //numPatternB.Value = Point_NT37900[GPN - index];
                        frmMain.frmain.OLED_Show_Click(frmMain.frmain.btnPatternW, e);       //显示255白画面，从255白画面开始调节
                        Thread.Sleep(200);
                        Msr_CA310();
                        Msr_CA310(); //修复讨厌的灰阶跳变时CA410数据异常的问题
                        ReceivOKFlag = false;
                        GammaTuning();
                    }
                    break;
                case 2:  //寄存器值与亮度反比
                    break;
                default:
                    break;
            }
        }
        private void Msr_CA310()
        {
            frmMain.frmain.Msr_CASDK();
            auto_lum = frmMain.frmain.CASDK_LUM;
            auto_x = frmMain.frmain.CASDK_x;
            auto_y = frmMain.frmain.CASDK_y;
        }   //获取CA310/CA410读数
        private void btnAutoGammaJumpTest_Click(object sender, EventArgs e)
        {
            JumpGammaAdjustFlag = true;
        }
        bool JumpGammaAdjustFlag = false;  //跳过某个绑点标志位，通常用于末尾低灰阶
        UInt32 timeout = 0;
        private void GammaTuning()   //AutoGamma处理过程
        {
            double Lr_t, Lg_t, Lb_t, lumr, lumg, lumb;
            while (index <= GPN)
            {
                if (STOPAutoGammaFlag)
                {
                    return;
                }
                Msr_CA310();
                txtlvshow.Text = "Lv: " + auto_lum.ToString("f4") + "\r\n" + "x: " + auto_x.ToString("f4") + "\r\n" + "y: " + auto_y.ToString("f4") + "\r\n";
                labTargetlum.Text = "Tar:" + D_lum[GPN - index].ToString("#0.0000").Substring(0, 6);  // 在UI上显示当前绑点的目标亮度值
                frmMain.frmain.textBox1.Text += "Adjust inex:" + GPN + "----" + index + "\r\n";

                lum_off = (D_lum[GPN - index] * Convert.ToDouble(numVT_loff.Value) / 1000);  //计算当前绑点允许的亮度误差范围
                x_off = Convert.ToDouble(txtVT_xoff.Text);
                y_off = Convert.ToDouble(txtVT_yoff.Text);       //获取色坐标允许误差范围

                if (index > 20)  //根据灰阶范围修正色坐标误差范围
                {   //根据灰阶范围修正色坐标误差范围
                    if (D_lum[GPN - 1] < 10)
                    {
                        x_off += x_off * 4;
                        y_off += y_off * 4;
                    }
                    else if (D_lum[GPN - 1] < 30)
                    {
                        {
                            x_off += x_off * 3;
                            y_off += y_off * 3;
                        }
                    }
                    else if (D_lum[GPN - 1] < 90)
                    {
                        {
                            x_off += x_off * 2;
                            y_off += y_off * 2;
                        }
                    }
                    else
                    {
                        {
                            x_off += x_off;
                            y_off += y_off;
                        }
                    }
                } //根据灰阶范围修正色坐标误差范围

                if ((auto_lum < (D_lum[GPN - index] + lum_off)) && (auto_lum > (D_lum[GPN - index] - lum_off)))//
                    flag1 = 0;  //判断亮度以及色坐标是否在目标范围
                if ((auto_y < (D_y + y_off)) && (auto_y > (D_y - y_off)) && flag1 == 0)//
                    flag2 = 0;  //判断亮度以及色坐标是否在目标范围
                if ((auto_x < (D_x + x_off)) && (auto_x > (D_x - x_off)) && flag1 == 0)//
                    flag3 = 0;  //判断亮度以及色坐标是否在目标范围
                if ((flag1 == 0 && flag2 == 0 && flag3 == 0) && (index < 10)) //低灰阶本来就很难调就不这么折腾了
                {   //初次判断调整OK后，再来复测一次，以消除偶发调不准问题
                    Msr_CA310();
                    if ((auto_lum < (D_lum[GPN - index] + lum_off)) && (auto_lum > (D_lum[GPN - index] - lum_off)))//
                        flag1 = 0;  //判断亮度以及色坐标是否在目标范围
                    else flag1 = 1;
                    if ((auto_y < (D_y + y_off)) && (auto_y > (D_y - y_off)) && flag1 == 0)//
                        flag2 = 0;  //判断亮度以及色坐标是否在目标范围
                    else flag2 = 1;
                    if ((auto_x < (D_x + x_off)) && (auto_x > (D_x - x_off)) && flag1 == 0)//
                        flag3 = 0;  //判断亮度以及色坐标是否在目标范围
                    else flag3 = 1;
                }//初次判断调整OK后，再来复测一次，以消除偶发调不准问题,

                Lr_t = R_y * ((auto_y - G_y) * (B_x - auto_x) + (auto_x - G_x) * (auto_y - B_y)) / B_y / ((auto_y - G_y) * (auto_x - R_x) + (auto_x - G_x) * (R_y - auto_y));
                Lb_t = 1.0;
                Lg_t = G_y * ((auto_y - R_y) * (B_x - auto_x) + (auto_x - R_x) * (auto_y - B_y)) / B_y / ((auto_y - R_y) * (auto_x - G_x) + (auto_x - R_x) * (G_y - auto_y));
                lumr = auto_lum * Lr_t / (Lr_t + Lg_t + Lb_t);
                lumg = auto_lum * Lg_t / (Lr_t + Lg_t + Lb_t);
                lumb = auto_lum * Lb_t / (Lr_t + Lg_t + Lb_t);

                if (((flag1 == 0 && flag2 == 0 && flag3 == 0) || JumpGammaAdjustFlag) || (timeout > 3 * numTurnGammaTimeout.Value))
                {
                    if (timeout > 3 * numTurnGammaTimeout.Value) { frmMain.frmain.textBox1.Text = "--模糊处理--\r\n" + "----模糊处理----\r\n" + "--------模糊处理--------\r\n" + "----模糊处理----\r\n" + "--模糊处理--\r\n"; }
                    timeout = 0;
                    index++;
                    if (index == GPN)   //  最后一个绑点通常为0，不用调试结束即可
                    {
                        TimTest.Stop();//停止计时
                        GammatuningOKFlag = true;
                        frmMain.frmain.showmsg("NT37900 gamma调试完毕!");
                        STOPAutoGammaFlag = true;
                        btn_NT37900_Stop.PerformClick();
                        return;
                    }
                    if (index < GPN)
                    {
                        frmMain.frmain.showmsg(index + "完成...\r\n");
                        for (int i = 0; i < 25; i++)    //本意用于显示当前绑点目标信息，但一般用不到
                        {
                            //Convert.ToString(要转的数, 16);//string s = string.Format("0x{0:X2}", i);    // s = 0x0F;
                            //Points_LV.Text += (i + 1) + ",R/G/B, V" + Point_NT37900[24 - i] + ": " + string.Format("0x{0:X2}", GammaValue[24 - i, 0]) + "--";
                            //Points_LV.Text += string.Format("0x{0:X2}", GammaValue[24 - i, 1]) + "--";
                            //Points_LV.Text += string.Format("0x{0:X2}", GammaValue[24 - i, 2]) + "\r\n";

                            //this.GammaReg_dataGridView.Rows.Clear();
                            //DataGirdShow((byte)i, GammaValue[i, 0], GammaValue[i, 1], GammaValue[i, 2]);
                            //Points_LV.Text += (i + 1) + ",R/G/B, V" + Point_NT37900[24 - i] + ": " + string.Format("0x{0:X2}", GammaValue[24 - i, 0]) + "--";
                            //Points_LV.Text += string.Format("0x{0:X2}", GammaValue[24 - i, 1]) + "--";
                            //Points_LV.Text += string.Format("0x{0:X2}", GammaValue[24 - i, 2]) + "\r\n";
                        }
                        //Thread.Sleep(10); //1秒=1000毫秒，
                        //T17.Enabled = true;
                        flag1 = 1;  //复位 亮度色坐标符合目标标志位
                        flag2 = 1;
                        flag3 = 1;
                        JumpGammaAdjustFlag = false;
                    }
                    rstep = (byte)(int.Parse(numStep.Value.ToString())); ;    //重新获取调节步长
                    gstep = (byte)(int.Parse(numStep.Value.ToString())); ;
                    bstep = (byte)(int.Parse(numStep.Value.ToString())); ;
                    frmMain.frmain.numPatternR.Value = Point_NT37900[GPN - index];     //设定绑点灰阶
                    //numPatternG.Value = Point_NT37900[GPN - index];
                    //numPatternB.Value = Point_NT37900[GPN - index];
                    frmMain.frmain.OLED_Show_Click(frmMain.frmain.btnPatternW, null);//写入Pattern参数   ，显示帮点对应灰阶画面
                    //ReceivOKFlag = false;
                    Thread.Sleep(10);
                    Msr_CA310();
                    Msr_CA310(); //修复讨厌的灰阶跳变时CA410数据异常的问题

                }
                else
                {
                    if ((GPN - index == 1) | (GPN - index == 2))//这里index最大值为绑点数量-1；倒数第2个绑点 以及倒数第3个绑点可以做技术处理
                    {
                        //GammaValue[0, 1] = 0;  //0绑点不调，直接送零
                        //GammaValue[0, 2] = 0;
                        //GammaValue[0, 0] = 0;
                        GammaValue[GPN - index, 0] = GammaValue[GPN - index + 1, 0] >> 1;  //绑点不调，直接赋值算了，如果有过度不均再手动修正即可
                        GammaValue[GPN - index, 1] = GammaValue[GPN - index + 1, 1] >> 1;
                        GammaValue[GPN - index, 2] = GammaValue[GPN - index + 1, 2] >> 1;
                        JumpGammaAdjustFlag = true;
                    }
                    //else if (GPN - index == 2) //倒数第2个绑点
                    //{
                    //}
                    else
                    {
                        if ((flag3 == 1) | (flag2 == 1) | (flag1 == 1))   //这个判断的意义可以猜猜看
                        {
                            {   //Gamma --R----
                                if (lumr > D_lums[GPN - index, 0])
                                {
                                    if ((!lastdirupR)) { timeout++; }
                                    if ((!lastdirupR) && (rstep >= 2)) rstep >>= 1;
                                    GammaValue[GPN - index, 0] = GammaValue[GPN - index, 0] - rstep;// (byte)(int.Parse(numStep.Value.ToString()));
                                    lastdirupR = true;
                                }
                                else
                                {
                                    if ((lastdirupR)) { timeout++; }
                                    if ((lastdirupR) && (rstep >= 2)) rstep >>= 1;
                                    GammaValue[GPN - index, 0] = GammaValue[GPN - index, 0] + rstep;
                                    lastdirupR = false;
                                }
                            }
                            {//Gamma ---G--
                                if (lumg > D_lums[GPN - index, 1])
                                {
                                    if ((!lastdirupG)) { timeout++; }
                                    if ((!lastdirupG) && (gstep >= 2)) gstep >>= 1;
                                    GammaValue[GPN - index, 1] = GammaValue[GPN - index, 1] - gstep;
                                    lastdirupG = true;
                                }
                                else
                                {
                                    if ((lastdirupG)) { timeout++; }
                                    if ((lastdirupG) && (gstep >= 2)) gstep >>= 1;
                                    GammaValue[GPN - index, 1] = GammaValue[GPN - index, 1] + gstep;
                                    lastdirupG = false;
                                }
                            }
                            {//--Gamma  ---B---
                                if (lumb > D_lums[GPN - index, 2])
                                {
                                    if ((!lastdirupB)) { timeout++; }
                                    if ((!lastdirupB) && (bstep >= 2)) bstep >>= 1;
                                    GammaValue[GPN - index, 2] = GammaValue[GPN - index, 2] - bstep;
                                    lastdirupB = true;
                                }
                                else
                                {
                                    if ((lastdirupB)) { timeout++; }
                                    if ((lastdirupB) && (bstep >= 2)) bstep >>= 1;
                                    GammaValue[GPN - index, 2] = GammaValue[GPN - index, 2] + bstep;
                                    lastdirupB = false;
                                }
                            }
                            frmMain.frmain.textBox1.Text += "rstep:" + rstep + "gstetp:" + gstep + "bstep:" + bstep + "\r\n";
                            frmMain.frmain.textBox1.Select(frmMain.frmain.textBox1.Text.Length, 0);
                            frmMain.frmain.textBox1.ScrollToCaret();
                        }   //如果Gamma Value不在目标范围内，此处修正之
                        CheckandCorrectGammaValue();
                        GammaValueFormat_Click(null, null);
                        //显示当前(待)写入的Gamma寄存器值
                        txtGammaValue.Text = GammaValue[GPN - index, 0] + "\r\n" + GammaValue[GPN - index, 1] + "\r\n" + GammaValue[GPN - index, 2] + "\r\n";
                        GammaValueSet(1, 1, 1, 1, 1, 1, GammaValueTeparr);
                        Thread.Sleep(20);
                        Application.DoEvents();//重点，必须加上，否则父子窗体都假死                            
                    }

                }
            }
            TimTest.Stop();//停止计时
        }

        private void btnVTStop_Click(object sender, EventArgs e)
        {
            STOPAutoGammaFlag = true;
            chkGammaLoadBMP.Checked = false;
            flag1 = 1;
            flag2 = 1;
            flag3 = 1;
            TimTest.Stop();//停止计时
            frmMain.frmain.textBox1.ForeColor = Color.Black;
            btnCalculateNT37900.PerformClick();
        }
        private void btnWriteGamma_Click(object sender, EventArgs e)   //检查GammaValue 并且重新转换成指定格式后写入DDIC
        {
            CheckandCorrectGammaValue();   //检查Gamma 是否存在高低灰阶数值错乱 ,并刷新表格数据              
            GammaValueFormat_Click(null, null);  //Gamma 值与实际地址进行转换 
            GammaValueSet(0, 0, 0, 0, 0, 0, GammaValueTeparr); //GammaValue 转换成特定格式后再通过此函数写入DDIC
        }
        uint GammaValueMax = 0xFFF - 1;
        private void CheckandCorrectGammaValue()   //检查GammaValue 是否按照大小排列
        {
            byte i; GPN = (byte)Point_NT37900.Length; // 获取Gamma绑点数量
            if (GammaValue[GPN - 1, 0] > GammaValueMax)
            {
                GammaValue[GPN - 1, 0] = GammaValueMax - 16;
            }
            if (GammaValue[GPN - 1, 1] > GammaValueMax)
            {
                GammaValue[GPN - 1, 1] = GammaValueMax - 16;
            }
            if (GammaValue[GPN - 1, 2] > GammaValueMax)
            {
                GammaValue[GPN - 1, 2] = GammaValueMax - 16;
            }  //确保GammaValue不要超过DDIC 中Gamma寄存能接受的最大值
            if (chkSaveGammavalue.Checked)//Gamma值检查
            {
                for (i = (byte)(GPN - 1); i > 0; i--)    //低灰阶GammaValue如果大于高灰阶GammaValue则强制变小
                {
                    if (GammaValue[i, 0] < GammaValue[i - 1, 0])
                    {
                        GammaValue[i - 1, 0] = GammaValue[i, 0] - 0;
                        //GammaValueFormat_Click(null, null);
                    }
                    if (GammaValue[i, 1] < GammaValue[i - 1, 1])
                    {
                        GammaValue[i - 1, 1] = GammaValue[i, 1] - 0;
                        //GammaValueFormat_Click(null, null);
                    }
                    if (GammaValue[i, 2] < GammaValue[i - 1, 2])
                    {
                        GammaValue[i - 1, 2] = GammaValue[i, 2] - 0;
                        //GammaValueFormat_Click(null, null);
                    }
                }
            }
            for (i = 15; i < 25; i++)    //没用到的绑点填写和实际最高绑点15的相同值
            {
                GammaValue[i, 0] = GammaValue[14, 0];
                GammaValue[i, 1] = GammaValue[14, 1];
                GammaValue[i, 2] = GammaValue[14, 2];
            }
            GammaValue[0, 0] = 0; GammaValue[0, 1] = 0; GammaValue[0, 2] = 0;
            if (chkGammaGridViewFresh.Checked)   // 刷新UI界面GammaValue值显示
            {
                this.GammaReg_dataGridView.Rows.Clear();
                for (i = 0; i < GPN; i++)
                {
                    DataGirdShow(i, GammaValue[i, 0], GammaValue[i, 1], GammaValue[i, 2]);
                }
            }
        }
        private void btnGammaValueUpdate_Click(object sender, EventArgs e)      //刷新UI上表格内的Gamma数据
        {
            int Line_Count = 0;
            try
            {
                Line_Count = GammaReg_dataGridView.RowCount;
            }
            catch
            {
                MessageBox.Show("表格数据(行数)异常！", "提示：");
                return;
            }
            try
            {
                for (int i = 0; i < Line_Count - 1; i++)//有一行标题
                {
                    GammaValue[i, 0] = Convert.ToUInt32(GammaReg_dataGridView.Rows[i].Cells[2].Value);
                    GammaValue[i, 1] = Convert.ToUInt32(GammaReg_dataGridView.Rows[i].Cells[3].Value);
                    GammaValue[i, 2] = Convert.ToUInt32(GammaReg_dataGridView.Rows[i].Cells[4].Value);
                }
                //MessageBox.Show("数据更新OK！", "提示：");
                frmMain.frmain.textBox1.Text += "Gamma数据更新OK！\r\n";
                btnWriteGamma.PerformClick();
            }
            catch
            {
                MessageBox.Show("Gamma数据更新错误！", "唐韬说：");
            }
        }
        private void numStep_ValueChanged(object sender, EventArgs e)   //手动调整AutoGamma调节步长以在初次调整Gamma是提升速度
        {
            rstep = (byte)(int.Parse(numStep.Value.ToString()));
            gstep = (byte)(int.Parse(numStep.Value.ToString()));
            bstep = (byte)(int.Parse(numStep.Value.ToString()));
        }
        private void chkNT37900dircshow_CheckedChanged(object sender, EventArgs e)     //Gamma保存时辅助选项 1
        {
            //if (chkNT37900dircshow.Checked)
            //    chkGammaFormatForNT37900.Checked = false;
        }
        private void chkGammaFormatForNT37900_CheckedChanged(object sender, EventArgs e)   ////Gamma保存时辅助选项 2
        {
            //  if (chkGammaFormatForNT37900.Checked)
            //    chkNT37900dircshow.Checked = false;
        }
        #region  //Gamma调整计时
        System.DateTime TimeNow = new DateTime();
        TimeSpan TimeCount = new TimeSpan();
        private void TimTest_Tick(object sender, EventArgs e)
        {
            TimeCount = DateTime.Now - TimeNow;
            txtTimeShow.Text = string.Format("{0:00}:{1:00}:{2:00}", TimeCount.Hours, TimeCount.Minutes, TimeCount.Seconds);
        }
        #endregion
        private byte[] arrbyte_tmp = new byte[250];         //临时保存下位机返回值
        public void DataGirdShow(byte index, double RRR, double GGG, double BBB)        //UI 表格显示 R/G/B对应Gamma寄存器值
        {
            int Row_Accum = 0, Current_Index = 0, Row_flag = 0;

            DataGridViewRow Row1 = new DataGridViewRow();

            Row_Accum = this.GammaReg_dataGridView.Rows.Count - 1;
            if (Row_Accum != 0)
            {
                Current_Index = this.GammaReg_dataGridView.SelectedCells[0].RowIndex;
                if ((Current_Index != Row_Accum - 1) && (Current_Index != Row_Accum))
                {
                    Row_Accum = Current_Index;
                    Row_flag = 1;
                }
                else
                {
                    this.GammaReg_dataGridView.Rows.Add(Row1);
                }
                if ((Row_Accum != 0) && (Row_flag != 1))
                {
                    if (Current_Index != Row_Accum)
                    {
                        this.GammaReg_dataGridView.Rows[Row_Accum - 1].Selected = false;
                        this.GammaReg_dataGridView.Rows[Row_Accum].Selected = true;
                    }
                }
            }
            else
            {
                this.GammaReg_dataGridView.Rows.Add(Row1);
            }
            this.GammaReg_dataGridView.Rows[Row_Accum].Cells[0].Value = index + 1;//序号
            //Rows[x]为第x行,Cells[x]为第x列
            this.GammaReg_dataGridView.Rows[Row_Accum].Cells[1].Value = (D_lum[index]).ToString("#0.0000").Substring(0, 6);
            this.GammaReg_dataGridView.Rows[Row_Accum].Cells[2].Value = RRR;
            this.GammaReg_dataGridView.Rows[Row_Accum].Cells[3].Value = GGG;
            this.GammaReg_dataGridView.Rows[Row_Accum].Cells[4].Value = BBB;

            if (Row_flag == 1)
            {
                Row_flag = 0;
                Row_Accum = this.GammaReg_dataGridView.Rows.Count - 1;
                this.GammaReg_dataGridView.Rows[Current_Index].Selected = false;
                this.GammaReg_dataGridView.Rows[Row_Accum - 1].Selected = true;
            }
            GammaReg_dataGridView.FirstDisplayedScrollingRowIndex = GammaReg_dataGridView.RowCount - 1;
        }

        #endregion  //--- Auto Gamma-----
        #region //通用命令处理
        private void Send_Cmd_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            switch (btn.Name)
            {
                case "btnSend1":
                    {
                        frmMain.frmain.txtProcessDrivercode(txtCmd1.Text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                    }
                    break;
                case "btnSend2":
                    {
                        frmMain.frmain.txtProcessDrivercode(txtCmd2.Text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                    }
                    break;
                case "btnSend3":
                    {
                        frmMain.frmain.txtProcessDrivercode(txtCmd3.Text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                    }
                    break;

            }
            Setting.TempRecord.cmdLen = 6;
            if (rBt_LP_DCS_Long_Write.Checked | rBt_LP_DCS_Short_Write.Checked | rBt_LP_Gerneric_Long_Write.Checked | rBt_LP_Gerneric_Short_Write.Checked)
            {

                frmMain.frmain.SendCmd(0);
            }
            else
            {
                frmMain.frmain.SendCmd(4);
            }
            frmMain.frmain.showmsg("命令已下发");
        }
        private void SaveCode_Click(object sender, EventArgs e)
        {
            SaveFileDialog txt = new SaveFileDialog();
            txt.Filter = @"txt文件(*.txt)|*.txt|所有文件(*.*)|*.*";
            string str = "//-----保存Driver IC Code文件------\r\n";
            if (txt.ShowDialog() == DialogResult.OK)
            {
                if (txt.FileName == " ")
                {
                    return;
                }
                StreamWriter sw = null; //文件流
                sw = new StreamWriter(txt.FileName, false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")
                try
                {
                    if (ChkCMD1.Checked)
                    {
                        str += "//---CMD1---\r\n" + txtCmd1.Text;// lstMIPIDriver.Items[i].ToString();
                        str += "\r\n\r\n";
                    }
                    if (ChkCMD2.Checked)
                    {
                        str += "//---CMD2---\r\n" + txtCmd2.Text;// lstMIPIDriver.Items[i].ToString();
                        str += "\r\n\r\n";
                    }
                    if (ChkCMD3.Checked)
                    {
                        str += "//---CMD3---\r\n" + txtCmd3.Text;// lstMIPIDriver.Items[i].ToString();
                        str += "\r\n\r\n";
                    }
                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流
                    MessageBox.Show("Driver IC Code保存OK！", "系统提示：");
                }
                catch
                {
                    MessageBox.Show("Driver IC Code保存时发生错误，请再试！", "系统提示：");
                }
            }
        }
        private void OpenTxtCode_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;

            OpenFileDialog of = new OpenFileDialog();
            of.Filter = "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*";
            of.Title = "初始化 Code";

            if (of.ShowDialog() == DialogResult.OK)
            {
                StreamReader streamReader = new StreamReader(of.FileName, Encoding.Default);
                switch (btn.Name)
                {
                    case "OpenTxtCode":
                        {
                            txtCmd1.Clear();
                            txtCmd1.Text = streamReader.ReadToEnd();
                        }
                        break;
                    case "OpenTxtCode2":
                        {
                            txtCmd2.Clear();
                            txtCmd2.Text = streamReader.ReadToEnd();
                        }
                        break;
                    case "OpenTxtCode3":
                        {
                            txtCmd3.Clear();
                            txtCmd3.Text = streamReader.ReadToEnd();
                        }
                        break;

                    default: break;
                }
                streamReader.Close();
            }
        }
        #endregion
        string path = "";
        #region //------自定义功能按键---------------
        string speedflag1, speedflag2, speedflag3, speedflag4, speedflag5, speedflag6, speedflag7, speedflag8;

        private void btnFunLoad_Click(object sender, EventArgs e)
        {
            {
                StreamReader streamReader = new StreamReader("./update/Fun.cfg", Encoding.Default);
                FunDefaultfilePath = streamReader.ReadLine();
                streamReader.Close();
            }
            FolderBrowserDialog fldb = new FolderBrowserDialog();
            //首次defaultfilePath为空，按FolderBrowserDialog默认设置（即桌面）选择            
            if (FunDefaultfilePath != "")
            {
                //设置此次默认目录为上一次选中目录
                fldb.SelectedPath = FunDefaultfilePath;
            }

            fldb.ShowNewFolderButton = false;
            DialogResult res = fldb.ShowDialog();
            if (res != System.Windows.Forms.DialogResult.OK)
            {
                MessageBox.Show("没选择任何文件夹.");
                return;
            }
            FunDefaultfilePath = fldb.SelectedPath;
            path = fldb.SelectedPath;
            if (!Directory.Exists(path))
            {
                MessageBox.Show("文件夹不存在.");
                return;
            }
            //DirectoryInfo di = new DirectoryInfo(path);
            //this.listBox3_BMPFile.Items.Clear();
            //this.CreateListItem(di);//递归加载文件夹里的所有图片
            //txttip.Text = path;            
            StreamWriter sw = null; //文件流
            sw = new StreamWriter("./update/Fun.cfg", false, Encoding.Default);//Encoding.GetEncoding("UTF-8")
            sw.Write(FunDefaultfilePath);
            sw.Dispose(); //释放资源
            sw.Close(); //关闭数据流
            // -------------------------------------------------------------------------
            try
            {
                //StreamReader streamReader = new StreamReader(path+"\\Fun1.txt", Encoding.Default);
                //FunDefaultfilePath = streamReader.ReadLine();
                //streamReader.Close();
                ReadFuncfg(path + "\\Fun1.txt", out String Ftitle1, out speedflag1, out funcmd1);
                btnFun1.Text = Ftitle1;

                ReadFuncfg(path + "\\Fun2.txt", out String Ftitle2, out speedflag2, out funcmd2);
                btnFun2.Text = Ftitle2;

                ReadFuncfg(path + "\\Fun3.txt", out String Ftitle3, out speedflag3, out funcmd3);
                btnFun3.Text = Ftitle3;

                ReadFuncfg(path + "\\Fun4.txt", out String Ftitle4, out speedflag4, out funcmd4);
                btnFun4.Text = Ftitle4;

                ReadFuncfg(path + "\\Fun5.txt", out String Ftitle5, out speedflag5, out funcmd5);
                btnFun5.Text = Ftitle5;

                ReadFuncfg(path + "\\Fun6.txt", out String Ftitle6, out speedflag6, out funcmd6);
                btnFun6.Text = Ftitle6;

                ReadFuncfg(path + "\\Fun7.txt", out String Ftitle7, out speedflag7, out funcmd7);
                btnFun7.Text = Ftitle7;

                ReadFuncfg(path + "\\Fun8.txt", out String Ftitle8, out speedflag8, out funcmd8);
                btnFun8.Text = Ftitle8;
                btnStore.Enabled = true;
            }
            catch
            {
                MessageBox.Show("向东提示配置文件缺失，请检查", "错误");
            }

        }

        private void CustomSendCmd_Click(object sender, EventArgs e)   //自定义功能按键
        {
            Button btn = (Button)sender; string spedflag = "";
            switch (btn.Name)
            {
                case "btnFun1":
                    {
                        frmMain.frmain.txtProcessDrivercode(funcmd1, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        spedflag = speedflag1;
                    }
                    break;
                case "btnFun2":
                    {
                        frmMain.frmain.txtProcessDrivercode(funcmd2, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        spedflag = speedflag2;
                    }
                    break;
                case "btnFun3":
                    {
                        frmMain.frmain.txtProcessDrivercode(funcmd3, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        spedflag = speedflag3;
                    }
                    break;
                case "btnFun4":
                    {
                        frmMain.frmain.txtProcessDrivercode(funcmd4, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        spedflag = speedflag4;
                    }
                    break;
                case "btnFun5":
                    {
                        frmMain.frmain.txtProcessDrivercode(funcmd5, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        spedflag = speedflag5;
                    }
                    break;
                case "btnFun6":
                    {
                        frmMain.frmain.txtProcessDrivercode(funcmd6, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        spedflag = speedflag6;
                    }
                    break;
                case "btnFun7":
                    {
                        frmMain.frmain.txtProcessDrivercode(funcmd7, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        spedflag = speedflag7;
                    }
                    break;
                case "btnFun8":
                    {
                        frmMain.frmain.txtProcessDrivercode(funcmd8, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        spedflag = speedflag8;
                    }
                    break;

            }
            //Setting.TempRecord.cmdLen = 6;
            if (spedflag == "LP")
            {
                frmMain.frmain.SendCmd(0);  //低速
            }
            else
            {
                frmMain.frmain.SendCmd(4); //高速
            }
            frmMain.frmain.showmsg("命令已下发。");
        }

        string FunDefaultfilePath = "";
        string funcmd1, funcmd2, funcmd3, funcmd4, funcmd5, funcmd6, funcmd7, funcmd8;

        private void Gamma51set(object sender, EventArgs e)
        {
            //if (rbt_NT37900_Gamma10.Checked) { regSend.Text = "51,0f,ff"; if (chkAutoSet51.Checked) { writeReg.PerformClick(); } }
            //else if (rbt_NT37900_Gamma9.Checked) { regSend.Text = "51,0f,ff"; if (chkAutoSet51.Checked) { writeReg.PerformClick(); } }
            //else if (rbt_NT37900_Gamma1.Checked) { regSend.Text = "51,00,09"; if (chkAutoSet51.Checked) { writeReg.PerformClick(); } if (chkAutoTarlum.Checked) txtVT_lum.Text = "" + 0x9 * Convert.ToDouble(DbvMaxlum.Text) / 0x7ff; }
            //else if (rbt_NT37900_Gamma2.Checked) { regSend.Text = "51,00,1b"; if (chkAutoSet51.Checked) { writeReg.PerformClick(); } if (chkAutoTarlum.Checked) txtVT_lum.Text = "" + 0x1b * Convert.ToDouble(DbvMaxlum.Text) / 0x7ff; }
            //else if (rbt_NT37900_Gamma3.Checked) { regSend.Text = "51,00,5b"; if (chkAutoSet51.Checked) { writeReg.PerformClick(); } if (chkAutoTarlum.Checked) txtVT_lum.Text = "" + 0x5b * Convert.ToDouble(DbvMaxlum.Text) / 0x7ff; }
            //else if (rbt_NT37900_Gamma4.Checked) { regSend.Text = "51,01,11"; if (chkAutoSet51.Checked) { writeReg.PerformClick(); } if (chkAutoTarlum.Checked) txtVT_lum.Text = "" + 0x111 * Convert.ToDouble(DbvMaxlum.Text) / 0x7ff; }
            //else if (rbt_NT37900_Gamma5.Checked) { regSend.Text = "51,01,f4"; if (chkAutoSet51.Checked) { writeReg.PerformClick(); } if (chkAutoTarlum.Checked) txtVT_lum.Text = "" + 0x1f4 * Convert.ToDouble(DbvMaxlum.Text) / 0x7ff; }
            //else if (rbt_NT37900_Gamma6.Checked) { regSend.Text = "51,04,00"; if (chkAutoSet51.Checked) { writeReg.PerformClick(); } if (chkAutoTarlum.Checked) txtVT_lum.Text = "" + 0x400 * Convert.ToDouble(DbvMaxlum.Text) / 0x7ff; }
            //else if (rbt_NT37900_Gamma7.Checked) { regSend.Text = "51,07,ff"; if (chkAutoSet51.Checked) { writeReg.PerformClick(); } if (chkAutoTarlum.Checked) txtVT_lum.Text = "" + 0x7ff * Convert.ToDouble(DbvMaxlum.Text) / 0x7ff; }
            //else if (rbt_NT37900_Gamma8.Checked) { regSend.Text = "51,08,00"; if (chkAutoSet51.Checked) { writeReg.PerformClick(); } }

            btnAutoGammas.Enabled = true;
            //btnIRCGamma.Enabled = true;

            //// 设定对应Gamma序号
            //if (rbt_NT37900_Gamma1.Checked)
            //{
            //    Gammnum = 0x00;
            //}
            //else if (rbt_NT37900_Gamma2.Checked)
            //{
            //    Gammnum = 0x01;
            //}
            //else if (rbt_NT37900_Gamma3.Checked)
            //{
            //    Gammnum = 0x02;
            //}
            //else if (rbt_NT37900_Gamma4.Checked)
            //{
            //    Gammnum = 0x03;
            //}
            //else if (rbt_NT37900_Gamma5.Checked)
            //{
            //    Gammnum = 0x04;
            //}
            //else if (rbt_NT37900_Gamma6.Checked)
            //{
            //    Gammnum = 0x05;
            //}
            //else if (rbt_NT37900_Gamma7.Checked)
            //{
            //    Gammnum = 0x06;
            //}
            //else if (rbt_NT37900_Gamma8.Checked)
            //{
            //    Gammnum = 0x07;
            //}
            //else if (rbt_NT37900_Gamma9.Checked)
            //{
            //    Gammnum = 0x08;
            //}
            //else if (rbt_NT37900_Gamma10.Checked)
            //{
            //    Gammnum = 0x09;
            //}
            numGammaPage.Value = Gammnum;
        }

        //------------------------------------------------------------
        private void ReadFuncfg(string addr, out String Ftitle, out String speedflag, out String Fcmd)
        {
            lines = new List<string>();

            //FileStream fs = new FileStream(Application.StartupPath + "\\x_Novatek\\Fun1.txt", FileMode.Open)
            FileStream fs = new FileStream(addr, FileMode.Open);
            StreamReader rd = new StreamReader(fs);
            string s;
            //读入文件所有行，存放到List<string>集合中
            while ((s = rd.ReadLine()) != null)
            {
                lines.Add(s);
            }
            rd.Close();
            fs.Close();
            //第一行在txttip中显示
            Ftitle = "";
            speedflag = "";
            if (lines.Count > 0)
            {
                Ftitle = lines[0];
                speedflag = lines[1];
            }
            //txtFuncmd.Text = "";
            Fcmd = "";
            for (int i = 2; i < lines.Count; i++)
            {
                Fcmd += lines[i] + "\r\n";
            }

        }
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            path = Application.StartupPath + "\\x_Novatek";
            try
            {
                //StreamReader streamReader = new StreamReader(path+"\\Fun1.txt", Encoding.Default);
                //FunDefaultfilePath = streamReader.ReadLine();
                //streamReader.Close();
                ReadFuncfg(path + "\\Fun1.cfg", out String Ftitle1, out speedflag1, out funcmd1);
                btnFun1.Text = Ftitle1;

                ReadFuncfg(path + "\\Fun2.cfg", out String Ftitle2, out speedflag2, out funcmd2);
                btnFun2.Text = Ftitle2;

                ReadFuncfg(path + "\\Fun3.cfg", out String Ftitle3, out speedflag3, out funcmd3);
                btnFun3.Text = Ftitle3;

                ReadFuncfg(path + "\\Fun4.cfg", out String Ftitle4, out speedflag4, out funcmd4);
                btnFun4.Text = Ftitle4;

                ReadFuncfg(path + "\\Fun5.cfg", out String Ftitle5, out speedflag5, out funcmd5);
                btnFun5.Text = Ftitle5;

                ReadFuncfg(path + "\\Fun6.cfg", out String Ftitle6, out speedflag6, out funcmd6);
                btnFun6.Text = Ftitle6;

                ReadFuncfg(path + "\\Fun7.cfg", out String Ftitle7, out speedflag7, out funcmd7);
                btnFun7.Text = Ftitle7;

                ReadFuncfg(path + "\\Fun8.cfg", out String Ftitle8, out speedflag8, out funcmd8);
                btnFun8.Text = Ftitle8;
                //btnStore.Enabled = true;

                MessageBox.Show("向东说刷新完成", "～～～");
            }
            catch
            {
                MessageBox.Show("向东提示配置文件缺失，请检查", "错误");
            }
        }

        private void NT37900_Gamma_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            this.Hide();
        }

        private void btnStore_Click(object sender, EventArgs e)
        {
            //FileStream fs = new FileStream(Application.StartupPath + "\\x_Novatek\\Fun1.txt", FileMode.Open)
            //SaveFileDialog txt = new SaveFileDialog();
            //txt.Filter = @"txt文件(*.txt)|*.txt|所有文件(*.*)|*.*";
            string str = "";
            //if (txt.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    StreamWriter sw = null; //文件流
                    sw = new StreamWriter(Application.StartupPath + "\\x_Novatek\\Fun1.cfg", false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")

                    {
                        str += btnFun1.Text + "\r\n";//
                        str += speedflag1 + "\r\n";
                        str += funcmd1;
                    }
                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流
                                // MessageBox.Show("自定义命令保存OK，但请确认文件名是否规范！", "系统提示：");

                    str = ""; sw = null; //文件流
                    sw = new StreamWriter(Application.StartupPath + "\\x_Novatek\\Fun2.cfg", false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")

                    {
                        str += btnFun2.Text + "\r\n";//
                        str += speedflag2 + "\r\n";
                        str += funcmd2;
                    }
                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流

                    str = ""; sw = null; //文件流
                    sw = new StreamWriter(Application.StartupPath + "\\x_Novatek\\Fun3.cfg", false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")

                    {
                        str += btnFun3.Text + "\r\n";//
                        str += speedflag3 + "\r\n";
                        str += funcmd3;
                    }
                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流

                    str = ""; sw = null; //文件流
                    sw = new StreamWriter(Application.StartupPath + "\\x_Novatek\\Fun4.cfg", false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")

                    {
                        str += btnFun4.Text + "\r\n";//
                        str += speedflag4 + "\r\n";
                        str += funcmd4;
                    }
                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流

                    str = ""; sw = null; //文件流
                    sw = new StreamWriter(Application.StartupPath + "\\x_Novatek\\Fun5.cfg", false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")
                    {
                        str += btnFun5.Text + "\r\n";//
                        str += speedflag5 + "\r\n";
                        str += funcmd5;
                    }
                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流

                    str = ""; sw = null; //文件流
                    sw = new StreamWriter(Application.StartupPath + "\\x_Novatek\\Fun6.cfg", false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")
                    {
                        str += btnFun6.Text + "\r\n";//
                        str += speedflag6 + "\r\n";
                        str += funcmd6;
                    }
                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流

                    str = ""; sw = null; //文件流
                    sw = new StreamWriter(Application.StartupPath + "\\x_Novatek\\Fun7.cfg", false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")
                    {
                        str += btnFun7.Text + "\r\n";//
                        str += speedflag7 + "\r\n";
                        str += funcmd7;
                    }
                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流

                    str = ""; sw = null; //文件流
                    sw = new StreamWriter(Application.StartupPath + "\\x_Novatek\\Fun8.cfg", false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")
                    {
                        str += btnFun8.Text + "\r\n";//
                        str += speedflag8 + "\r\n";
                        str += funcmd8;
                    }
                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流

                    MessageBox.Show("向东说固化命令成功！", "系统提示：");
                    btnRefresh.Enabled = true;
                    btnStore.Enabled = false;
                }
                catch
                {
                    MessageBox.Show("固化命令时发生错误，请再试！", "系统提示：");
                }
            }
        }

        private void btnFunTestcmdSend_Click(object sender, EventArgs e)
        {
            String[] lines = txtFuncmd.Text.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
            string speedflag = lines[1];
            String text = "";
            for (int i = 0; i < lines.Length; i++)
            {
                //假设删除第2行第3行
                if (i == 0 || i == 1)
                {
                    continue;
                }
                text += lines[i] + (i == lines.Length - 1 ? "" : "\r\n"); //最后一行不添加换行符
            }
            frmMain.frmain.txtProcessDrivercode(text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
            if (speedflag == "LP")
            {
                frmMain.frmain.SendCmd(0);  //低速
            }
            else
            {
                frmMain.frmain.SendCmd(4); //高速
            }
            frmMain.frmain.showmsg("命令已下发");
        }

        private void btnFunTestcmdSave_Click(object sender, EventArgs e)
        {
            SaveFileDialog txt = new SaveFileDialog();
            txt.Filter = @"txt文件(*.txt)|*.txt|所有文件(*.*)|*.*";
            string str = "";
            if (txt.ShowDialog() == DialogResult.OK)
            {
                if (txt.FileName == " ")
                {
                    return;
                }
                StreamWriter sw = null; //文件流
                sw = new StreamWriter(txt.FileName, false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")
                try
                {

                    {
                        str += txtFuncmd.Text;// lstMIPIDriver.Items[i].ToString();
                        str += "\r\n";
                    }

                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流
                    MessageBox.Show("自定义命令保存OK，但请确认文件名是否规范！", "系统提示：");
                }
                catch
                {
                    MessageBox.Show("保存时发生错误，请再试！", "系统提示：");
                }
            }
        }
        #endregion
        #region    //浏览图片
        //string path = "";

        //-----------------------------------------
        #endregion

        bool readokflag = false;
        string defaultfilePath = "";
        #region  //----------------------

        private void NT37900_GammaR_Click(object sender, EventArgs e)
        {
            byte[] TepArr;
            try
            {
                TepArr = new byte[] { 3, 0xf0, 0xaa, 0x13,
                    4, 0XFF, 0XFF, 0XFF, 25,
                    2, 0xbf, 0x08,   //第9条Gamma
                    //4, 0XFF, 0XFF, 0XFF, 15,
                    //2, 0xc4, 0x01,
                    4, 0XFF, 0XFF, 0XFF, 15 };  //byte[] TepArr;

                // 设定对应Gamma序号
                //if (rbt_NT37900_Gamma1.Checked)
                //{
                //    Gammnum = 0x00;
                //}
                //else if (rbt_NT37900_Gamma2.Checked)
                //{
                //    Gammnum = 0x01;
                //}
                //else if (rbt_NT37900_Gamma3.Checked)
                //{
                //    Gammnum = 0x02;
                //}
                //else if (rbt_NT37900_Gamma4.Checked)
                //{
                //    Gammnum = 0x03;
                //}
                //else if (rbt_NT37900_Gamma5.Checked)
                //{
                //    Gammnum = 0x04;
                //}
                //else if (rbt_NT37900_Gamma6.Checked)
                //{
                //    Gammnum = 0x05;
                //}
                //else if (rbt_NT37900_Gamma7.Checked)
                //{
                //    Gammnum = 0x06;
                //}
                //else if (rbt_NT37900_Gamma8.Checked)
                //{
                //    Gammnum = 0x07;
                //}
                //else if (rbt_NT37900_Gamma9.Checked)
                //{
                //    Gammnum = 0x08;
                //}
                //else if (rbt_NT37900_Gamma10.Checked)
                //{
                //    Gammnum = 0x09;
                //}
                //TepArr[11] = Gammnum; //设定对应Gamma序号
                TepArr[11] = (byte)numGammaPage.Value; //设定对应Gamma序号
                frmMain.frmain.comPort.Write(GetCRCArray(TepArr, 4), 0, TepArr.Length + 6);//循环部分，每段数据结尾  
                                                                                           //-----------------  Application.DoEvents();
                Thread.Sleep(50);
                Application.DoEvents();
                GammaReadBackFlag = true;
                frmMain.frmain.GeneralRegRead(0xb0, 16);
                Application.DoEvents();
                Thread.Sleep(60);

                GammaReadBackFlag = true;
                frmMain.frmain.GeneralRegRead(0xb1, 16);
                Application.DoEvents();
                Thread.Sleep(60);

                GammaReadBackFlag = true;
                frmMain.frmain.GeneralRegRead(0xb2, 16);
                Application.DoEvents();
                Thread.Sleep(60);

                GammaReadBackFlag = true;
                frmMain.frmain.GeneralRegRead(0xb3, 2);
                Application.DoEvents();
                Thread.Sleep(60);

                GammaReadBackFlag = true;
                frmMain.frmain.GeneralRegRead(0xb4, 16);
                Application.DoEvents();
                Thread.Sleep(60);

                GammaReadBackFlag = true;
                frmMain.frmain.GeneralRegRead(0xb5, 16);
                Application.DoEvents();
                Thread.Sleep(60);

                GammaReadBackFlag = true;
                frmMain.frmain.GeneralRegRead(0xb6, 16);
                Application.DoEvents();
                Thread.Sleep(60);

                GammaReadBackFlag = true;
                frmMain.frmain.GeneralRegRead(0xb7, 2);
                Application.DoEvents();
                Thread.Sleep(60);

                GammaReadBackFlag = true;
                frmMain.frmain.GeneralRegRead(0xb8, 16);
                Application.DoEvents();
                Thread.Sleep(60);

                GammaReadBackFlag = true;
                frmMain.frmain.GeneralRegRead(0xb9, 16);
                Application.DoEvents();
                Thread.Sleep(60);

                GammaReadBackFlag = true;
                frmMain.frmain.GeneralRegRead(0xbA, 16);
                Application.DoEvents();
                Thread.Sleep(60);

                GammaReadBackFlag = true;
                frmMain.frmain.GeneralRegRead(0xbB, 2);
                Application.DoEvents();
                Thread.Sleep(60);

            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
            }
            //GammaReadBackFlag = true;
            //frmMain.frmain.GeneralRegRead(0xb0, 16);
            //Thread.Sleep(1500);
            //GammaReadBackFlag = true;
            //frmMain.frmain.GeneralRegRead(0xb3, 2);
        }

        private void chkAODMode_CheckedChanged(object sender, EventArgs e)
        {
            if (!chkAODMode.Checked)
            {
                regSend.Text = "38";
                writeReg.PerformClick();
                regSend.Text = "2c";
                writeReg.PerformClick();
                //    rbt_NT37900_Gamma1.Enabled = true; rbt_NT37900_Gamma2.Enabled = true; rbt_NT37900_Gamma3.Enabled = true; rbt_NT37900_Gamma4.Enabled = true; rbt_NT37900_Gamma5.Enabled = true; rbt_NT37900_Gamma6.Enabled = true; rbt_NT37900_Gamma7.Enabled = true; rbt_NT37900_Gamma8.Enabled = true; rbt_NT37900_Gamma9.Enabled = true; rbt_NT37900_Gamma10.Enabled = true;
            }
            else
            {
                numGammaPage.Value = 0x82;
                txtCmd3.Text = "FF,AA,55,A5,81\r\n" +
                    "6F,13\r\n" +
                    "F9,00\r\n" +
                    "F0,55,AA,52,08,03\r\n" +
                    "C7,00\r\n" +
                    "FF,FF,FF,FF\r\n" +
                    "39\r\n2C";
                Send_Cmd_Click(btnSend3, null);
                Thread.Sleep(50);
                regSend.Text = "51,0d,bb,0d,bb,0F,FE";
                writeReg.PerformClick();
                txtVT_lum.Text = "69.2";
                //MessageBox.Show("请确认当前51值设定是否正确", "提示");
                btnAutoGammas.Enabled = true;
                // rbt_NT37900_Gamma1.Enabled = false; rbt_NT37900_Gamma2.Enabled = false; rbt_NT37900_Gamma3.Enabled = false; rbt_NT37900_Gamma4.Enabled = false; rbt_NT37900_Gamma5.Enabled = false; rbt_NT37900_Gamma6.Enabled = false; rbt_NT37900_Gamma7.Enabled = false; rbt_NT37900_Gamma8.Enabled = false; rbt_NT37900_Gamma9.Enabled = false; rbt_NT37900_Gamma10.Enabled = false;
            }
        }
        string tiptxtFlag = "";  //保存返回值提示信息       
        private void NT37900_Load(object sender, EventArgs e)
        {
            //tabPageIRC.Parent = null;
        }

        Single[,] Gammadbv2Arr = new Single[1, 1];
        byte TotalGammaNum;
        private void txt51Dbv_TextChanged(object sender, EventArgs e)
        {
            string Gammadbv;
            string[] GammadbvGroup = new string[5];
            TotalGammaNum = (byte)txt51Dbv.Lines.Length;
            for (int i = 0; i < TotalGammaNum; i++)
            {
                if (txt51Dbv.Lines[i] == "")
                {
                    TotalGammaNum = (byte)i;
                    break;
                }
            }
            GammadbvGroup = new string[TotalGammaNum];
            Gammadbv2Arr = new Single[TotalGammaNum, 3];
            for (int i = 0; i < TotalGammaNum; i++)
            {
                // GammadbvGroup[i] = txt51Dbv.Lines[i];
                Gammadbv = txt51Dbv.Lines[i]; //GammadbvGroup[i];
                Gammadbv = Gammadbv.Replace(" ", ""); //去空格
                Gammadbv = Gammadbv.Replace(",", " "); // “;”换成空格
                GammadbvGroup = Gammadbv.Trim().Split(' ');
                if (GammadbvGroup[0] == "")
                { break; }
                else
                {
                    try
                    {
                        //byte.Parse((Convert.ToInt32(strTmp, 16)).ToString());  
                        Gammadbv2Arr[i, 0] = (Convert.ToInt32(GammadbvGroup[0], 16));
                        Gammadbv2Arr[i, 1] = (Convert.ToSingle(GammadbvGroup[1])); //  Convert.float(GammadbvGroup[1]);
                        Gammadbv2Arr[i, 2] = (Convert.ToSingle(GammadbvGroup[2]));
                    }
                    catch (FormatException ee)
                    { Console.WriteLine(ee.Message); }
                }
            }
            frmMain.frmain.showmsg((TotalGammaNum) + "条Gamma待调试");
        }

        bool GammatuningOKFlag = false;
        uint[,,] GammaValx = new uint[10, 25, 3];  //提前预定义GammaValue存储区，防止被意外覆盖

        private void chkGammaLoadBMP_CheckedChanged(object sender, EventArgs e)
        {
            if (chkGammaLoadBMP.Checked)
            {
                frmMain.frmain.chkDSCmode.Checked = true;
            }
            else { frmMain.frmain.chkDSCmode.Checked = false; }
        }

        //预定义10条Gamma，25个绑点，R/G/B3个值
        //GammaValx[0]

        private void GammavalMove(int movedir, int n, uint[,,] a_GroupGammaVal, uint[,] b_GammaVal)
        {
            if (movedir == 0)
            {
                for (int inx = 0; inx < GPN; inx++)
                {
                    b_GammaVal[inx, 0] = a_GroupGammaVal[n, inx, 0];
                    b_GammaVal[inx, 1] = a_GroupGammaVal[n, inx, 1];
                    b_GammaVal[inx, 2] = a_GroupGammaVal[n, inx, 2];
                }
            }
            else
            {
                for (int inx = 0; inx < GPN; inx++)
                {
                    a_GroupGammaVal[n, inx, 0] = b_GammaVal[inx, 0];
                    a_GroupGammaVal[n, inx, 1] = b_GammaVal[inx, 1];
                    a_GroupGammaVal[n, inx, 2] = b_GammaVal[inx, 2];
                }
            }
        }

        private void btnGroupGammaTune_Click(object sender, EventArgs e)
        {
            GPN = (byte)Point_NT37900.Length; // 获取Gamma绑点数量
            //gm0 = GroGv.GammaValue0;
            txt51Dbv_TextChanged(null, null);
            for (int t = 0; t < TotalGammaNum; t++)
            {
                //GammaValue = GroGv.GammaValue0;
                GammatuningOKFlag = false;

                txtVT_lum.Text = Gammadbv2Arr[t, 2] + "";
                numGammaPage.Value = (decimal)Gammadbv2Arr[t, 1];

                GammavalMove(0, t, GammaValx, GammaValue); //多组GammaValue保存缓冲区搬出指定低t条Gamma至GammaValue
                //return;
                //btnCalculateNT37900.PerformClick();
                btnCalGammaValue_Click(null, null);
                btnGammaValueUpdate.PerformClick();
                //btnGammaValueUpdate_Click(null,null);

                Dbv51setting((int)Gammadbv2Arr[t, 0]);  //设定51

                btnAutoGammas.PerformClick();
                //while (!GammatuningOKFlag) Application.DoEvents();//重点，必须加上，否则父子窗体都假死;
                if (chkSaveGammavalue.Checked)
                {
                    btnSaveGamma.PerformClick();
                    //btnSaveGamma_Click(btnSaveGamma,null);
                    //Application.DoEvents();//重点，必须加上，否则父子窗体都假死;
                }

                GammavalMove(1, t, GammaValx, GammaValue); //更新多组GammaValue保存缓冲区的第t条Gamma

                frmMain.frmain.showmsg("第" + (t + 1) + "条Gamma调试完成");
                Console.WriteLine("第" + (t + 1) + "条Gamma调试完成");
                //GroGv.GammaValue0=GammaValue;
                //GammV2GammaS((byte)t);
            }
            frmMain.frmain.showmsg("--多条Gamma调试完成---");
        }
        private void Dbv51setting(int value)
        {
            byte v51h, v51l;
            v51h = Convert.ToByte(value >> 8);
            v51l = Convert.ToByte(value & 0xff);
            byte[] tepArr = new byte[] { //2, 0xB0, 0x20,
            //2,0,0,
            3,0x51,v51h,v51l
            };
            frmMain.frmain.comPort.Write(GetCRCArray(tepArr, 4), 0, tepArr.Length + 6);//循环部分，每段数据结尾  
            Thread.Sleep(20);
            Application.DoEvents();//重点，必须加上，否则父子窗体都假死
        }
        private uint[,] GammaValue0 = new uint[25, 3];//保存  Normal  Gammavalue
        private uint[,] GammaValue1 = new uint[25, 3];//保存当前Gammavalue

        string[] nodeGray = new string[25];
        //private byte ActualUseNodeNum;
        private void txtGammaNode_TextChanged(object sender, EventArgs e)
        {
            byte ActualUseNodeNum;
            string Graylv;
            Graylv = txtGammaNode.Text;
            Graylv = Graylv.Replace(" ", ""); //去空格
            Graylv = Graylv.Replace(",", " "); // “;”换成空格
            nodeGray = Graylv.Trim().Split(' ');
            // R66462_Point
            ActualUseNodeNum = (byte)nodeGray.Length;
            labGammaPoint.Text = "当前绑点数量：" + ActualUseNodeNum;
            Point_NT37900 = new int[ActualUseNodeNum];
            try
            {
                for (byte i = 0; i < ActualUseNodeNum; i++)
                {
                    Point_NT37900[i] = Convert.ToByte(nodeGray[i]);
                }
            }
            catch { }
        }

        private uint[,] GammaValue2 = new uint[25, 3];//保存当前Gammavalue
        private uint[,] GammaValue3 = new uint[25, 3];//保存当前Gammavalue
        private uint[,] GammaValue4 = new uint[25, 3];//保存当前Gammavalue
        private uint[,] GammaValue5 = new uint[25, 3];//保存当前Gammavalue
        private uint[,] GammaValue6 = new uint[25, 3];//保存当前Gammavalue
        private uint[,] GammaValue7 = new uint[25, 3];//保存当前Gammavalue
        private uint[,] GammaValue8 = new uint[25, 3];//保存当前Gammavalue
        private uint[,] GammaValue9 = new uint[25, 3];//保存当前Gammavalue

        private void btnEditDBVsetting_Click(object sender, EventArgs e)
        {
            if (btnEditDBVsetting.Tag != null)
            {//编辑结束
                btnEditDBVsetting.Tag = null;
                btnGroupGammaTune.Enabled = true;
                txt51Dbv.Enabled = false;
                btnEditDBVsetting.Text = "DBV编辑";
                txt51Dbv_TextChanged(null, null);
                label14.SendToBack();//将控件放置所有控件最底端 
            }
            else
            {
                btnEditDBVsetting.Tag = "editing";
                btnGroupGammaTune.Enabled = false;
                txt51Dbv.Enabled = true;
                btnEditDBVsetting.Text = "保存锁定";
                label14.BringToFront();//将控件放置所有控件最前端  
            }
        }

        private void chkAODMode_MouseEnter(object sender, EventArgs e)
        {
            ToolTip p = new ToolTip();
            p.ShowAlways = true;
            p.SetToolTip(this.chkAODMode, "勾选时会自动发送39命令进入AOD模式，取消勾选会自动下发38命令退出AOD模式");
        }

        #endregion //-


    }
}
